import socket
import struct
import threading
import sys


def handle_init_message(conn):
    data = conn.recv(6)
    type_, N = struct.unpack('>HI', data)
    if type_ != 1:
        raise Exception("协议错误")
    conn.sendall(struct.pack('>H', 2))
    return N


def handle_request(conn):
    header = conn.recv(6)
    type_, length = struct.unpack('>HI', header)
    if type_ != 3:
        raise Exception("协议错误")
    data = conn.recv(length).decode()
    reversed_data = data[::-1]
    packet = struct.pack('>HI', 4, len(reversed_data)) + reversed_data.encode()
    conn.sendall(packet)
    return reversed_data


def handle_client(conn, addr):
    try:
        print(f"新连接来自: {addr}")
        N = handle_init_message(conn)
        for _ in range(N):
            reversed_data = handle_request(conn)
    except Exception as e:
        print(f"与 {addr} 的连接出错: {e}")
    finally:
        conn.close()
        print(f"关闭与 {addr} 的连接")


def main():
    # 获取端口号，默认为12345
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 12345

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(('127.0.0.1', port))  # 使用回环地址
        s.listen()
        print(f"服务器启动，监听端口 {port}...")

        while True:
            conn, addr = s.accept()
            threading.Thread(target=handle_client, args=(conn, addr)).start()


if __name__ == "__main__":
    main()